﻿using System;
using System.Collections.Generic;
using System.Linq;

// added for IoC
using System.Web.Configuration;
using System.Web.Http;
using Ninject;
using WebApiContrib.IoC.Ninject;
using UserSessionService.WebApi.DataLayer;

namespace UserSessionService.WebApi
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // dk - added IoC for presistency services
            IKernel kernel = new StandardKernel();
            string repositoryClassName = WebConfigurationManager.AppSettings["RepositoryClass"];

            // dk - for some reason this doesn't work
            //System.Type repoClass = Type.GetType(repositoryClassName);           
            //var t = typeof(a);
            //kernel.Bind<IUserSessionRepository>().To<repoClass>();
            // ... so ugly comes ...
            if (repositoryClassName.Equals("UserSessionService.WebApi.DataLayer.AzureTablesRepository"))
            {
                //kernel.Bind<IUserSessionRepository>().To<AzureTablesRepository>();

                // dk - with this option GetService() will always return the object created here 
                kernel.Bind<IUserSessionRepository>().ToConstant(new AzureTablesRepository());
            }
            else if (repositoryClassName.Equals("UserSessionService.WebApi.DataLayer.InMemoryRepository"))
            {
                //kernel.Bind<IUserSessionRepository>().To<InMemoryRepository>();
                kernel.Bind<IUserSessionRepository>().ToConstant(new InMemoryRepository()); // dk - now even InMemory will work
            }
            else if (repositoryClassName.Equals("UserSessionService.WebApi.DataLayer.RedisRepository"))
            {
                //kernel.Bind<IUserSessionRepository>().To<RedisRepository>();
                kernel.Bind<IUserSessionRepository>().ToConstant(new RedisRepository());
            }
            config.DependencyResolver = new NinjectResolver(kernel);

            config.Routes.MapHttpRoute(
                name: "UserSessionAPI",
                routeTemplate: "api/{controller}/{encodedUserId}",
                defaults: new { encodedUserId = RouteParameter.Optional }
            );

            // To disable tracing in your application, please comment out or remove the following line of code
            // For more information, refer to: http://www.asp.net/web-api
            config.EnableSystemDiagnosticsTracing();
        }
    }
}
